package samplebasic

import sweet.mvc.api._

//==> config
class SampleBasicSweetConfig extends SweetConfig {
  loadSysProps("sample-basic.config", "classpath:/config.properties")   

  addLayouts(
    "main"->"/view/layout/main.ftl",
    "plaintext"->"/view/layout/plaintext.ftl",
    "admin"->"/view/layout/admin.ftl"
  )
  
  def setupConfig {
                      
    // toolbox.auto.update.begin << DO NOT REMOVE IF YOU WANT Toolbox to auto- generate files
    addControllers("/admin" -> new AdminController(props, servletContextRealPath))
    addControllers("/quickview" -> new QuickViewController(servletContextRealPath))  
    addControllers("/form-demo2" -> new FormDemo2Controller)
    addControllers("/form-demo" -> new FormDemoController)
    addControllers("/guessgame" -> new GuessGameController)
    addControllers("/main" -> new MainController)
    // toolbox.auto.update.end
    
    addInterceptorWithExceptList(new AdminInterceptor, "/admin", List("/login"))
    
    //Get appVersion for this webapp and save it.
    val appVersion = getAppVersion(servletContextRealPath)
    logger.debug("Setting appVersion to " + appVersion)
    addProps("appVersion" -> appVersion)
    servletContext.setAttribute("appVersion", appVersion)
  }
  
  /** Get user application version string. */
  def getAppVersion(ctxPath: String) = {
    val attr = sweet.helper.ManifestHelper.manifestAttributes(ctxPath)
    //logger.debug("Manifest as props " + (Map() ++ attr).toString)
    attr.getOrElse("Implementation-Name", "sample-basic-development.latest")
  }
}

class AdminInterceptor extends BeforeInterceptor {
  def beforeReq(req: Req): Option[View] = {
    val loginOpt = req.sess.attr[Boolean]("adminLogin")
    if(loginOpt == None) Some(View("redirect:/admin/login"))
    else None
  }
}
